package progress.exa29_2.part2.ui;

import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class Server extends Application {

    private TextArea textArea = new TextArea();
    private int clientNo = 0;

    public void start(Stage primaryStage) {

        Scene scene=new Scene(new ScrollPane(textArea),450,200);
        primaryStage.setTitle("Server");
        primaryStage.setScene(scene);
        primaryStage.show();

        /*
        建立一个线程创建服务器实例并启动监听
         */
        new Thread(()->{
            try{
                //创建服务器套接字，服务器端口号设为8000
                ServerSocket serverSocket = new ServerSocket(8000);
                Platform.runLater(()->textArea.appendText("Server started at"+new Date()+'\n'));

                //进入无线循环
                while(true){

                    //服务器进入监听状态
                    Socket socket = serverSocket.accept();
                    //有客户端连接服务端，客户数加一
                    clientNo++;

                    Platform.runLater(()->{
                        textArea.appendText("客户端连接数: "+clientNo+"  "+new Date()+'\n');

                        InetAddress inetAddress = socket.getInetAddress();
                        textArea.appendText("客户端 "+clientNo+" 号 的主机名为： "+inetAddress.getHostName()+'\n');
                        textArea.appendText("客户端 "+clientNo+"号的IP地址为： "+inetAddress.getHostAddress()+'\n');
                    });

                    //为客户端创建新线程进行持续交互
                    new Thread(new HandleAClient(socket)).start();

                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }).start();


    }

    /**
     * 持续交互任务定义
     */
    class HandleAClient implements Runnable{

        //此任务的客户端套接字
        private Socket socket;

        public HandleAClient(Socket socket) {
            this.socket=socket;
        }

        public void run() {
            try{
                //创建服务器接受和发送数据的流
                DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());
                DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

                //持续监听客户端发送的数据
                while(true) {
                    double radius = inputFromClient.readDouble();

                    double area=radius*radius*Math.PI;

                    outputToClient.writeDouble(area);

                    Platform.runLater(()->{
                        textArea.appendText("得到客户端的半径数据： "+radius+'\n');
                        textArea.appendText("计算出来的面积为: "+area+'\n');
                    });
                }
            }catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}
